package com.heima.wemedia.interceptor;

import com.heima.model.admin.pojos.AdUser;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.AdminThreadLocalUtil;
import com.heima.utils.thread.WmThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 黄晏凯
 */
@Slf4j
public class WmTokenInterceptor implements HandlerInterceptor {

    /**
     * 前置处理 获取用户信息，存入线程中
     *
     * @param request  请求
     * @param response 响应
     * @param handler  处理程序
     * @return boolean
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String userId = request.getHeader("userId");
        log.info("userId:{}", userId);

        if (StringUtils.isEmpty(userId)) {
            log.warn("非法用户访问!请求路径:{}", request.getRequestURI());
            response.setStatus(403);
            return false;
        }

        WmUser wmUser = new WmUser();
        wmUser.setId(Integer.parseInt(userId));
        WmThreadLocalUtil.setUser(wmUser);

        return true;
    }

    /**
     * 后置处理，清理threadlocal中的数据，防止内存溢出
     *
     * @param request  请求
     * @param response 响应
     * @param handler  处理程序
     * @param ex       前女友
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        WmThreadLocalUtil.clear();
    }
}